﻿using UnityEditor.Callbacks;
using UnityEditor;
using UnityEngine;
using System.IO;

public class uMicrophonePostprocessor
{
    [PostProcessBuild]
    public static void onPostProcessBuild(BuildTarget buildTarget, string pathToBuiltProject)
    {
        if (buildTarget != BuildTarget.WebGL)
        {
            Debug.LogWarning("Target is not WebGL!");
            return;
        }
        string packagePath = Path.GetFullPath("Packages/cn.net.xuefei.umicrophone");
        Debug.Log("packagePath:" + packagePath);
        // 自定义JavaScript文件的路径
        string customJSPath = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), packagePath + "/Assets/recorder.wav.min.js");
        // 确保自定义JavaScript文件存在
        if (!File.Exists(customJSPath))
        {
            Debug.LogError("Custom JavaScript file not found at " + customJSPath);
            return;
        }

        // 将自定义JavaScript文件复制到构建输出目录
        File.Copy(customJSPath, Path.Combine(pathToBuiltProject, "recorder.wav.min.js"), true);

        // 可以在这里添加额外的处理步骤，比如修改index.html文件等
        string htmlPath = Path.Combine(pathToBuiltProject, "index.html");

        // 确保文件存在
        if (!File.Exists(htmlPath))
        {
            Debug.LogError("index.html not found at " + htmlPath);
            return;
        }

        string htmlContent = File.ReadAllText(htmlPath);

        // addToScript
        string addToScriptPath = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), packagePath + "/Assets/AddToScript.txt");
        if (!File.Exists(addToScriptPath))
        {
            Debug.LogError("AddToScript.txt not found at " + addToScriptPath);
            return;
        }
        string addToScriptContent = File.ReadAllText(addToScriptPath);

        htmlContent = htmlContent.Insert(htmlContent.IndexOf("</script>"), addToScriptContent+ "\n    ");

        // 在这里修改htmlContent
        // 例如，添加一个新的脚本标签
        htmlContent = htmlContent.Insert(htmlContent.IndexOf("<script>"), "<script src=\"./recorder.wav.min.js\"></script>\n    ");

        htmlContent = htmlContent.Insert(htmlContent.IndexOf("loadingBar.style.display = \"none\";"), "          UnityIns = unityInstance;initRecord();\n                    ");

        File.WriteAllText(htmlPath, htmlContent);

        Debug.Log("index.html modified successfully.");
    }
}